package com.weaver.qfengx;

import com.alibaba.fastjson.JSON;
import com.engine.common.util.ServiceUtil;
import com.engine.workflow.entity.publicApi.PAResponseEntity;
import com.engine.workflow.entity.publicApi.ReqOperateRequestEntity;
import com.engine.workflow.publicApi.WorkflowRequestOperatePA;
import com.engine.workflow.publicApi.impl.WorkflowRequestOperatePAImpl;
import com.google.common.collect.Lists;
import com.weaver.qfengx.entity.RequestBaseInfo;
import com.weaver.qfengx.entity.WorkflowBaseInfo;
import com.weaver.qfengx.entity.WorkflowBillfield;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.workflow.WorkflowComInfo;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 流程相关操作工具类
 * Created by YeShengtao on 2020/8/24 15:01
 */
public class WorkflowUtils {

    private final static LogUtils log = new LogUtils(WorkflowUtils.class);


    /**
     * 查询表单信息
     */
    public static List<WorkflowBillfield> tableFieldList(String tablename) {
        if (StringUtils.isEmpty(tablename)) {
            return Lists.newArrayList();
        }
        if (tablename.contains("_dt")) { // 明细表
            return DaoUtils.querySqlToBean("select id,billid,fieldName,fieldLabel,fieldDbType," +
                            "fieldHtmlType,type,viewtype from workflow_billfield where " +
                            "detailtable  = ?)",
                    WorkflowBillfield.class, tablename);
        } else { // 主表
            return DaoUtils.querySqlToBean("select id,billid,fieldName,fieldLabel,fieldDbType," +
                            "fieldHtmlType,type,viewtype from workflow_billfield where billid " +
                            "= (select id from workflow_bill where tablename = ?) and (detailtable is null or detailtable = '')",
                    WorkflowBillfield.class, tablename);
        }
    }

    /**
     * 流程请求基本信息
     */
    public static RequestBaseInfo requestBaseInfo(String requestId) {
        RequestBaseInfo res = new RequestBaseInfo();
        Map<String, String> data = DaoUtils.executeQueryToMap("select requestid,lastnodeid,lastnodetype,status," +
                "currentnodeid,currentnodetype,requestname,creater," +
                "createdate,createtime,lastoperator,lastoperatedate,lastoperatetime,requestnamenew " +
                "from workflow_requestbase where requestid = ?", requestId);
        if (Objects.isNull(data)) {
            return null;
        }
        res.setRequestId(requestId);
        res.setLastNodeId(StringUtils.val(data.get("lastnodeid")));
        res.setLastNodeType(StringUtils.val(data.get("lastnodetype")));
        res.setStatus(StringUtils.val(data.get("status")));
        res.setCreater(StringUtils.val(data.get("creater")));
        res.setCreateDate(StringUtils.val(data.get("createdate")));
        res.setCreateTime(StringUtils.val(data.get("createtime")));
        res.setLastOperator(StringUtils.val(data.get("lastoperator")));
        res.setLastOperateDate(StringUtils.val(data.get("lastoperatedate")));
        res.setLastOperateTime(StringUtils.val(data.get("lastoperatetime")));
        res.setRequestNameNew(StringUtils.val(data.get("requestnamenew")));
        return res;
    }

    /**
     * 流程基本信息
     */
    public static WorkflowBaseInfo workflowBaseInfo(String workflowId) {
        WorkflowBaseInfo res = new WorkflowBaseInfo();
        Map<String, String> data = DaoUtils.executeQueryToMap("select id, formid, workflowname, workflowdesc, workflowtype, docPath from workflow_base where id = ?", workflowId);
        if (Objects.isNull(data)) {
            return null;
        }
        if (NumberUtils.parseInt(StringUtils.val(data.get("formid"))) < 0) {
            res.setMaintable("formtable_main_" + (-NumberUtils.parseInt(StringUtils.val(data.get("formid")))));
        }
        res.setFormId(StringUtils.val(data.get("formid")));
        res.setWorkflowId(workflowId);
        res.setDocPath(StringUtils.val(data.get("docPath")));
        res.setWorkflowName(StringUtils.val(data.get("workflowname")));
        res.setWorkflowType(StringUtils.val(data.get("workflowtype")));
        res.setWorkflowDesc(StringUtils.val(data.get("workflowdesc")));
        return res;
    }

    public static String requestIdToworkflowId(String requestId) {
        String sql = "select requestid, workflowid from workflow_requestbase where requestid = ?";
        return Objects.requireNonNull(DaoUtils.executeQueryToMap(sql, requestId)).get("workflowid");
    }

    public static String mainTable(RequestInfo requestInfo) {
        WorkflowComInfo workflowComInfo = new WorkflowComInfo();
        Util.getIntValue(workflowComInfo.getFormId("" + requestInfo.getWorkflowid()));
        return "formtable_main_" + -1 * Util.getIntValue(workflowComInfo.getFormId("" + requestInfo.getWorkflowid()));
    }

    public static String mainTableByRid(String request) {
        return DaoUtils.querySingleVal("select workflow_bill.tablename from workflow_requestbase " +
                "left join workflow_base on workflow_requestbase.workflowid = workflow_base.id " +
                "left join workflow_bill on workflow_base.formid = workflow_bill.id " +
                "where workflow_requestbase.requestid = ?", request);
    }

    public static String mainTable(String workflowId) {
        String sql = "select formid from workflow_base where id = ?";
        return "formtable_main_" + -1 * Util.getIntValue(Objects.requireNonNull(DaoUtils.executeQueryToMap(sql, workflowId)).get("formid"));
    }

    public static Map<String, String> data(String requestId, String workflowId) {
        String table = mainTable(workflowId);
        String sql = String.format("select * from %s where requestid = ?", mainTable(workflowId));
        return DaoUtils.executeQueryToMap(sql, requestId);
    }

    public static String creatorId(String requestId) {
        String sql = "select creater from workflow_requestbase where requestid = ?";
        return Objects.requireNonNull(DaoUtils.executeQueryToMap(sql, requestId)).get("creater");
    }

    public static String createNodeId(String workflowid) {
        String sql = "select a.nodeid from workflow_flownode a " +
                "left join workflow_nodebase b on b.id = a.nodeid where a.workflowid = ? " +
                "and (b.IsFreeNode is null or b.IsFreeNode!='1') and a.nodetype = 0";
        return DaoUtils.querySingleVal(sql, workflowid);
    }

    public static String requestName(String requestid) {
        return DaoUtils.querySingleVal("select requestname from workflow_requestbase where requestid = ?", requestid);
    }

    public static String prop(Property[] properties, String name) {
        for (Property property : properties) {
            if (StringUtils.equals(property.getName(), name)) {
                return Util.null2String(property.getValue());
            }
        }
        return "";
    }

    public static String currentNodeId(String requestId) {
        return DaoUtils.querySingleVal("select currentnodeid from workflow_requestbase where requestid = ?", requestId);
    }

    // 获取流程当前节点
    public static String currentNodeType(String requestid) {
        return DaoUtils.querySingleVal("select currentnodetype from workflow_requestbase where requestid = ?", requestid);
    }

    // 获取流程当前审批人员列表
    public static List<String> approverUserList(String requestid) {
        List<Map<String, String>> mapList = DaoUtils.executeQueryToMapList("select distinct w2.userid from workflow_requestbase w1, workflow_currentoperator w2 "
                + "where w1.requestid = w2.requestid and w1.currentnodeid = w2.nodeid  and w1.requestid = '" + requestid
                + "' and w2.isremark=0 and w2.preisremark=0 and w2.islasttimes=1");
        return mapList.stream().map(x -> StringUtils.valNotEmpty(x.get("userid"), "")).collect(Collectors.toList());
    }

    /**
     * 流程强制归档
     */
    public static boolean archiving(String requestid, User user) {
//        User user = User.getUser(1, 0);//系统管理员
        ReqOperateRequestEntity reqOperateRequestEntity = new ReqOperateRequestEntity();
        reqOperateRequestEntity.setRequestId(NumberUtils.parseInt(requestid, -1));//被调用的requestid
        Map<String, Object> otherparams = new HashMap<String, Object>();
        otherparams.put("ismonitor", 1);
        reqOperateRequestEntity.setOtherParams(otherparams);
//        Timer timer = new Timer();
//        timer.schedule(new HitachidoForceOverAction.Task(user, reqOperateRequestEntity), secondes * 1000);
        WorkflowRequestOperatePA workflowRequestOperatePA = (WorkflowRequestOperatePAImpl) ServiceUtil.getService(WorkflowRequestOperatePAImpl.class);
        PAResponseEntity paResponseEntity = workflowRequestOperatePA.doForceOver(user, reqOperateRequestEntity); //调用强制归档
        log.writeLog("requestid => " + requestid + ", 强制归档返回状态 ===> " + paResponseEntity.getCode());
        log.writeLog("requestid => " + requestid + ", 强制归档返回结果 ===> " + JSON.toJSONString(paResponseEntity));
        if (!StringUtils.equals("SUCCESS", paResponseEntity.getCode()))
            return false;
        return true;
    }

    public static boolean archiving(String requestid) {
        return archiving(requestid, User.getUser(1, 0));
    }
}
